package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@Api(tags = "通用相关接口")
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(@RequestBody MultipartFile file) {
        log.info("文件上传，参数为：{}", file.getOriginalFilename());
        try {
            //获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            //分离文件后缀和文件名
            String[] split = originalFilename.split("\\.");
            //使用UUID将文件名进行加密，防止出现文件名冲突的情况
            String ObjectFile = UUID.nameUUIDFromBytes(split[0].getBytes())+"."+split[split.length-1];
            //文件请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), ObjectFile);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败，{}", e.getMessage());
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);

    }

}
